package implementation.sort.QuickSort;

import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;
import implementation.sort.AbstractSorter;

import java.util.Comparator;
import java.util.List;


public class QuickSorter extends AbstractSorter {

    public QuickSorter(){
        this(SorterType.QUICK);
    }

    protected QuickSorter(SorterType sorterType) {
        super(sorterType);
    }


    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size() - 1);
    }

    private <T> void sort(Comparator<T> comparator, List<T> list, int start, int end) {
        if (end <= start) return;
        int i = partition(comparator, list, start, end);
        sort(comparator, list, start, i - 1);
        sort(comparator, list, i, end);
    }

    protected <T> int partition(Comparator<T> comparator, List<T> list, int start, int end) {
        int i = start;
        int j = end;
        while (i < j) {
            while (!greater(comparator, list, i, end)) {
                i++;
                if (i == end) break;
            }
            while (!greater(comparator, list, end, j)) {
                j--;
                if (j == start) break;
            }
            if (i >= j) break;
            swap(list, i, j);
        }
        swap(list, i, end);
        return i;
    }
}






